using UnityEngine;
using System.Collections;


public class ItemSelector : MonoBehaviour {

    // ----- configurable via Unity --------------------------------------------
    public Fader xFader;
    public Fader yFader;


    // ----- public variables --------------------------------------------------
    public int numItemsX;
    public int numItemsY;


    // ----- internal variables -----------------------------------------------
    bool isPushed;
    int[] indices = new int[2];


    // ----- internal helpers -----------------------------------------------
    int xIndex {
        get { return indices[0]; }
        set { indices[0] = value; }
    }

    int yIndex {
        get { return indices[1]; }
        set { indices[1] = value; }
    }

    float minXValue {
        get { return (xIndex == 0) ? 0.0f : xIndex * singleItemWidth; }
    }

    float maxXValue {
        get { return (xIndex == numItemsX-1) ? 1.0f : (xIndex+1) * singleItemWidth; }
    }

    float minYValue {
        get { return (yIndex == 0) ? 0.0f : yIndex * singleItemHeight; }
    }

    float maxYValue {
        get { return (yIndex == numItemsY-1) ? 1.0f : (yIndex+1) * singleItemHeight; }
    }

    float singleItemWidth {
        get { return 1.0f / (float)numItemsX; }
    }

    float singleItemHeight {
        get { return 1.0f / (float)numItemsY; }
    }


    // ----- internal methods --------------------------------------------------
    void Start() {
        if (xFader == null) Debug.LogError("X fader is not assigned in MenuHandler.");
        if (yFader == null) Debug.LogError("Y fader is not assigned in MenuHandler.");
    }

    void Hand_Update(Vector3 pos) {
        if (isPushed) return;

        if (xFader.value <= minXValue) {
            xIndex--;
        }
        else if (xFader.value >= maxXValue) {
            xIndex++;
        }
        else if (yFader.value <= minYValue) {
            yIndex--;
        }
        else if (yFader.value >= maxYValue) {
            yIndex++;
        }
        else {
            return;
        }

        // clamp so that indices don't overflow
        int[] clamped = new int[2] {Mathf.Clamp(xIndex, 0, numItemsX-1), Mathf.Clamp(yIndex, 0, numItemsY-1)};

        // then callback
        SendMessage("ItemSelector_Select", clamped, SendMessageOptions.DontRequireReceiver);
    }

    void PushDetector_Push() {
        isPushed = true;
    }

    void PushDetector_Release()  {
        isPushed = false;
    }
}
